package com.xindacloud.sms.console.system.controller;


import com.xindacloud.sms.console.constant.SessionKeys;
import com.xindacloud.sms.console.result.Result;
import com.xindacloud.sms.console.result.ResultGenerator;
import com.xindacloud.sms.console.system.dto.*;
import com.xindacloud.sms.console.system.entity.SmsUser;
import com.xindacloud.sms.console.system.service.ISmsUserService;
import com.xindacloud.sms.console.system.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author czc
 * @since 2019-10-08
 */
@Api(tags = {"用户模块"})
@RestController
@RequestMapping("/api/v1/sms-user")
public class SmsUserController {

    private final ISmsUserService userService;


    @Autowired
    public SmsUserController(ISmsUserService userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "用户登陆并保存至Session中", response = SmsUser.class)
    @PostMapping(value = "/login")
    public Result login(@ApiParam(name = "loginDTO", value = "用户登录对象", required = true)
                        @RequestBody UserLoginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        SmsUser smsUser = userService.login(loginDTO);
        response.setHeader("Access-Control-Expose-Headers", SessionKeys.SMS_TOKEN);
        if (Objects.nonNull(smsUser)) {
            session.setAttribute(SessionKeys.ACCOUNT, smsUser);
            return ResultGenerator.genSuccessResult(smsUser);
        } else {
            return ResultGenerator.genServerFailResult("无效的用户名和密码");
        }
    }

    @ApiOperation(value = "用户登出并删除Session中的用户信息")
    @PostMapping(value = "/logout")
    public Result logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        //SmsUser smsUser = getUserFromSession(request);
        if (Objects.nonNull(session)) {
            session.invalidate();
            //return ResultGenerator.genClientFailResult(HttpStatus.OK, "退出成功");
        }
        //return ResultGenerator.genClientFailResult(HttpStatus.UNAUTHORIZED, "未登录.");
        return ResultGenerator.genClientFailResult(HttpStatus.OK, "退出成功");
    }

    @ApiOperation(value = "用户列表", response = SmsUser.class)
    @PostMapping(value = "/getUserList")
    public Result getUserList(@ApiParam(name = "userDTO", value = "用户列表DTO", required = true)
                              @RequestBody UserDTO userDTO, HttpServletRequest request) {
        HttpSession session = request.getSession();
        SmsUser user = (SmsUser) session.getAttribute(SessionKeys.ACCOUNT);
        userDTO.setParentUserId(user.getUserId());
        return userService.getUserList(userDTO);
    }

    @ApiOperation(value = "添加或修改用户")
    @PostMapping(value = "/addOrUpdateUser")
    public Result addOrUpdateUser(@RequestBody SmsUser smsUser, HttpServletRequest request) {
        if (Objects.isNull(smsUser.getUserId()) || smsUser.getUserId() == 0) {
            HttpSession session = request.getSession();
            SmsUser user = (SmsUser) session.getAttribute(SessionKeys.ACCOUNT);
            smsUser.setParentUserId(user.getUserId());
        }
        return userService.addOrUpdateUser(smsUser);
    }

    @ApiOperation(value = "根据用户名查询用户列表", response = UserVO.class)
    @GetMapping(value = "/users/{username}")
    public Result getUserList(@ApiParam(name = "username", value = "用户名", required = true)
                              @PathVariable(name = "username", value = "username") String username) {
        final List<UserVO> userVOList = userService.queryUserInfoByName(username);
        return ResultGenerator.genSuccessResult(userVOList);
    }


    @ApiOperation(value = "用户分配角色")
    @PostMapping(value = "/addOrUpdateUserRoles")
    public Result addOrUpdateUserRoles(@RequestBody SmsUserRolesDTO smsUserRolesDTO) {
        return userService.addOrUpdateUserRoles(smsUserRolesDTO);
    }

    @ApiOperation(value = "删除用户")
    @PostMapping(value = "/deleteUsers")
    public Result deleteUsers(@RequestBody UserDeleteDTO userDeleteDTO) {
        return userService.deleteUsers(userDeleteDTO);
    }

    @ApiOperation(value = "同步所有运营商价格列表")
    @PostMapping(value = "/users/{userId}/sync-pricing")
    public Result syncPricing(@ApiParam(name = "userId", value = "用户ID", required = true)
                              @PathVariable(name = "userId", value = "userId") String userId) {
        return ResultGenerator.genSuccessResult(userService.syncPricingByUserId(Integer.parseInt(userId)));
    }

    @ApiOperation(value = "根据条件查询当前用户隶属于销售的运营商价格列表")
    @PostMapping(value = "/users/{userId}/pricing/list")
    public Result queryPricingListByUserId(@ApiParam(name = "userId", value = "用户ID", required = true)
                                           @PathVariable(name = "userId", value = "userId") String userId,
                                           @ApiParam(name = "queryPricingByConditionsDTO", value = "查询价格条件DTO", required = true)
                                           @RequestBody QueryPricingByConditionsDTO queryPricingByConditionsDTO) {
        return ResultGenerator.genSuccessResult(userService.queryUserAllowOperatorByUserId(Integer.parseInt(userId), queryPricingByConditionsDTO));
    }

    @ApiOperation(value = "同步当前用户隶属于销售的运营商价格列表")
    @PostMapping(value = "/users/{userId}/sync-pricing/batch")
    public Result syncPricingByBatch(@ApiParam(name = "userId", value = "用户ID", required = true)
                                     @PathVariable(name = "userId", value = "userId") String userId,
                                     @ApiParam(name = "syncUserPricingByConditionsDTO", value = "同步价格条件DTO", required = true)
                                     @RequestBody SyncUserPricingByConditionsDTO syncUserPricingByConditionsDTO) {
        return ResultGenerator.genSuccessResult(userService.syncUserPricingByOperatorIds(Integer.parseInt(userId),
                syncUserPricingByConditionsDTO.getOperatorIds()));
    }

    @ApiOperation(value = "同步当前用户隶属于销售的所有运营商价格列表")
    @PostMapping(value = "/users/{userId}/sync-pricing/all")
    public Result syncAllPricing(@ApiParam(name = "userId", value = "用户ID", required = true)
                                 @PathVariable(name = "userId", value = "userId") String userId) {
        return ResultGenerator.genSuccessResult(userService.syncUserPricingByOperatorIds(Integer.parseInt(userId), null));
    }


    @ApiOperation(value = "根据用户ID查询用户详情", response = UserVO.class)
    @PostMapping(value = "/getUserDetail")
    public Result getUserDetail(@ApiParam(name = "userId", value = "用户ID", required = true)
                                @RequestBody UserDTO userDTO) {
        return userService.getUserDetail(userDTO.getUserId());
    }

}
